package com.origin.netlibrary

import android.app.Application
import android.os.Environment
import com.origin.netlibrary.interceptor.NetInterceptor
import com.origin.netlibrary.netapi.DownloadService
import com.origin.netlibrary.netapi.RequestFormat
import okhttp3.Cache
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

class RetrofitManager private constructor(
        application: Application

) {
    //    application: Application,
//    BASE_URL: String,
//    provideBaseUrl: MoreBaseUrlInterceptor.BaseUrl,
//    dynamicTimeout: DynamicTimeoutInterceptor.DynamicTimeout?
    private val okHttpBuilder: OkHttpClient.Builder = OkHttpClient.Builder()
            .readTimeout(100, TimeUnit.SECONDS)
            .connectTimeout(100, TimeUnit.SECONDS)
    private var retrofit: Retrofit
    val requestFormat: RequestFormat by lazy {
        getHttpService(RequestFormat::class.java)
    }
    val downloadService: DownloadService by lazy {
        getHttpService(DownloadService::class.java)
    }


    // 创建自定义的TrustManager，用于信任所有证书
    val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
        override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {
            // 不检查客户端证书
        }

        override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {
            // 信任所有服务器证书
        }

        override fun getAcceptedIssuers(): Array<X509Certificate> {
            return arrayOf() // 返回空数组
        }
    })


    val sslContext = SSLContext.getInstance("TLS")


    init {
        sslContext.init(null, trustAllCerts, SecureRandom())
//        val moreBaseUrlInterceptor = MoreBaseUrlInterceptor(provideBaseUrl)
        okHttpBuilder

//            .addInterceptor(EnhancedCacheInterceptor(mCacheManager))
//            .addInterceptor(moreBaseUrlInterceptor)
//            .addInterceptor(DynamicTimeoutInterceptor(dynamicTimeout))

                .sslSocketFactory(sslContext.socketFactory, trustAllCerts[0] as X509TrustManager)
//            .sslSocketFactory(TrustAllCerts.createSSLSocketFactory())
//            .hostnameVerifier( TrustAllCerts.TrustAllHostnameVerifier())
                .hostnameVerifier { _, _ -> true }
                .addInterceptor(NetInterceptor.init())
        val retrofitBuilder = Retrofit.Builder()
                .baseUrl("http://www.apiopen.top/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
        retrofit = getUsually(retrofitBuilder, okHttpBuilder)
    }

    fun <T> getHttpService(service: Class<T>): T = retrofit.create<T>(service)


    companion object {
        @Volatile
        private var instance: RetrofitManager? = null
        fun getInstance(

                application: Application,
//           baseUrl: String,
//           provideBaseUrl: MoreBaseUrlInterceptor.BaseUrl,
//           dynamicTimeout: DynamicTimeoutInterceptor.DynamicTimeout
        ) =

                instance ?: synchronized(this) {
                    instance
                            ?: RetrofitManager(application
//                       , dynamicTimeout
                            ).also {


                                instance = it
                            }
                }
    }


}


/**
 * 通用请求接口
 */
private fun getUsually(
        builder: Retrofit.Builder,
        okHttpBuilder: OkHttpClient.Builder
): Retrofit {

//    val cacheDir = File(Environment.getDataDirectory().absolutePath, "response")
//    //缓存的最大尺寸10m
//    val cache = Cache(cacheDir, (1024 * 1024 * 10).toLong())
//
//    okHttpBuilder.cache(cache)

    return builder.client(okHttpBuilder.build()).build()

}

